<template>
    <div class="dialog-wrap" :style="{'--left':!store.sidebarStatus ? '150px' : '63px'}">
        <el-dialog :class="store.theme" v-model="dialogVisible" title="添加书签" width="50%" :append-to-body="true"
            :align-center="true" :close-on-click-modal="false" :show-close="false">
            <div class="input-wrap">
                <el-input v-model="url" placeholder="请输入网址" @keyup.enter="addBookmark">
                    <template #prepend>
                        <el-select v-model="protocol" placeholder="请选择协议" style="width: 115px">
                            <el-option label="http" value="http://" />
                            <el-option label="https" value="https://" />
                        </el-select>
                    </template>
                </el-input>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button :disabled="isLoading" @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" :loading="isLoading" @click="addBookmark">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useWebStore } from "../../store/webStore";
import { ElNotification } from 'element-plus'

const store = useWebStore()

const url = ref('')
const protocol = ref('http://')
const dialogVisible = ref(false)
const isLoading = ref(false)
watch(dialogVisible, (val) => {
    if (!val) {
        url.value = ''
    }
})

const open = () => {
    dialogVisible.value = true
}

const addBookmark = async () => {
    const href = protocol.value + url.value
    const findData = store.websites.find(item => item.url === href)

    // 判断是否已存在书签
    if (findData) {
        return ElNotification({
            title: '提示',
            message: `书签「${findData.title}」已存在，请勿重复添加`,
            type: 'info',
        })

    }
    isLoading.value = true
    const data = await Bookmark.sendUrl(href)
    if (data.screenshot) {
        store.setWebSite(data)
        dialogVisible.value = false
    } else {
        Bookmark.alert(data.message)
    }
    isLoading.value = false


}

defineExpose({
    open
})
</script>
<style lang='scss' scoped>
.dialog-wrap {
    position: relative;

    .input-wrap {
        display: flex;
        align-items: center;
        height: 60px;
    }

}

::v-deep(.el-overlay) {
    left: var(--left) !important;
}


::v-deep(.el-overlay-dialog) {
    left: var(--left) !important;
}
</style>